// pages/storage/storage.js
const app = getApp();

Page({
  data: {
    currentRoomId: null,
    roomInput: "",
    recentRooms: [],
    items: [],
    filteredItems: [],
    searchQuery: "",
    filter: "all", // all, text, file
    loading: false,
    syncing: false,
    quickText: "",
    showEditTextModal: false,
    isEditing: false, // In this page, edit is only for text
    activeItem: null,
    stats: {
      textCount: 0,
      fileCount: 0,
      totalSize: 0,
    },
    baseUrl: "",
  },

  noop() {},

  onLoad() {
    this.setData({ baseUrl: app.globalData.baseUrl });
    this.loadCurrentRoom();
    this.loadRecentRooms();
  },

  onShow() {
    if (this.data.currentRoomId) {
      this.loadItems();
    }
  },

  // 加载当前房间
  loadCurrentRoom() {
    const roomId = wx.getStorageSync("storageRoomId");
    if (roomId) {
      this.setData({ currentRoomId: roomId });
      this.loadItems();
    }
  },

  // 加载最近访问的房间
  async loadRecentRooms() {
    try {
      const response = await app.request({
        url: "/api/storage/rooms",
      });
      this.setData({
        recentRooms: response.data || [],
      });
    } catch (error) {
      console.error("加载最近房间失败:", error);
    }
  },

  // 房间输入变化
  onRoomInputChange(e) {
    this.setData({
      roomInput: e.detail.value,
    });
  },

  // 进入房间
  async enterRoom() {
    const roomId = this.data.roomInput.trim();
    if (!roomId) {
      app.showToast("请输入房间号码");
      return;
    }

    try {
      app.showLoading("进入房间中...");
      await app.request({
        url: "/api/storage/room/access",
        method: "POST",
        data: { roomId },
      });

      wx.setStorageSync("storageRoomId", roomId);
      this.setData({
        currentRoomId: roomId,
        roomInput: "",
      });
      this.loadItems();
      this.loadRecentRooms();
    } catch (error) {
      console.error("进入房间失败:", error);
      app.showToast("进入房间失败");
    } finally {
      app.hideLoading();
    }
  },

  // 选择最近房间
  selectRoom(e) {
    const roomId = e.currentTarget.dataset.roomId;
    wx.setStorageSync("storageRoomId", roomId);
    this.setData({ currentRoomId: roomId });
    this.loadItems();
  },

  // 显示房间选择器
  showRoomSelector() {
    this.setData({ currentRoomId: null });
    wx.removeStorageSync("storageRoomId");
  },

  // 加载暂存项目列表
  async loadItems() {
    if (!this.data.currentRoomId) return;

    try {
      this.setData({ loading: true });
      const response = await app.request({
        url: `/api/storage/items/${this.data.currentRoomId}`,
      });

      const items = (response.data || []).map((item) => {
        // 格式化时间
        item.formatted_time = this.formatTime(item.createdAt);

        // 生成预览内容
        if (item.type === "text") {
          item.preview_content =
            item.content.substring(0, 100) +
            (item.content.length > 100 ? "..." : "");
        }

        // 判断是否为图片
        if (item.type === "file" && item.fileType) {
          item.isImage = item.fileType.startsWith("image/");
        }

        return item;
      });

      this.setData({ items });
      this.filterItems();
      this.calculateStats();
    } catch (error) {
      console.error("加载暂存项目失败:", error);
      app.showToast("加载失败");
    } finally {
      this.setData({ loading: false });
    }
  },

  // 快速文本输入
  onQuickTextInput(e) {
    this.setData({ quickText: e.detail.value });
  },

  // 快速添加文本
  async quickAddText() {
    const content = this.data.quickText.trim();
    if (!content) {
      app.showToast("请输入文本内容");
      return;
    }

    try {
      app.showLoading("添加中...");
      await app.request({
        url: `/api/storage/text/${this.data.currentRoomId}`,
        method: "POST",
        data: {
          title: content.substring(0, 20) + (content.length > 20 ? "..." : ""),
          content,
        },
      });

      app.showToast("添加成功", "success");
      this.setData({ quickText: "" });
      this.loadItems();
    } catch (error) {
      console.error("快速添加文本失败:", error);
      app.showToast("添加失败");
    } finally {
      app.hideLoading();
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({ searchQuery: e.detail.value });
    this.filterItems();
  },

  // 设置筛选条件
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ filter });
    this.filterItems();
  },

  // 筛选项目
  filterItems() {
    let filtered = [...this.data.items];

    // 按类型筛选
    if (this.data.filter === "text") {
      filtered = filtered.filter((item) => item.type === "text");
    } else if (this.data.filter === "file") {
      filtered = filtered.filter((item) => item.type === "file");
    }

    // 按搜索关键词筛选
    if (this.data.searchQuery) {
      const query = this.data.searchQuery.toLowerCase();
      filtered = filtered.filter(
        (item) =>
          (item.title && item.title.toLowerCase().includes(query)) ||
          (item.content && item.content.toLowerCase().includes(query)) ||
          (item.fileName && item.fileName.toLowerCase().includes(query))
      );
    }

    this.setData({ filteredItems: filtered });
  },

  // 计算统计信息
  calculateStats() {
    const items = this.data.items;
    const textCount = items.filter((item) => item.type === "text").length;
    const fileCount = items.filter((item) => item.type === "file").length;
    const totalSize = items.reduce((sum, item) => sum + (item.size || 0), 0);

    this.setData({
      stats: {
        textCount,
        fileCount,
        totalSize,
      },
    });
  },

  // 模态框控制
  showEditTextModal(item) {
    this.setData({
      showEditTextModal: true,
      isEditing: true,
      activeItem: { ...item },
    });
  },

  hideEditTextModal() {
    this.setData({
      showEditTextModal: false,
      isEditing: false,
      activeItem: null,
    });
  },

  // 输入处理
  onTextTitleInput(e) {
    this.setData({ "activeItem.title": e.detail.value });
  },

  onTextContentInput(e) {
    this.setData({ "activeItem.content": e.detail.value });
  },

  // 保存文本 (用于编辑)
  async saveTextItem() {
    const item = this.data.activeItem;
    if (!item || !item.content.trim()) {
      app.showToast("内容不能为空");
      return;
    }

    try {
      app.showLoading("保存中...");
      await app.request({
        url: `/api/storage/items/${item.id}`,
        method: "PUT",
        data: {
          title: item.title,
          content: item.content,
        },
      });
      app.showToast("保存成功", "success");
      this.hideEditTextModal();
      this.loadItems();
    } catch (error) {
      console.error("保存失败:", error);
      app.showToast("保存失败");
    } finally {
      app.hideLoading();
    }
  },

  // 选择并上传文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 5, // Allow multiple files
      type: "all",
      success: (res) => {
        const files = res.tempFiles;
        for (const file of files) {
          this.uploadFile(file);
        }
      },
      fail: (err) => {
        if (err.errMsg.indexOf("cancel") === -1) {
          app.showToast("选择文件失败");
        }
      },
    });
  },

  async uploadFile(file) {
    try {
      app.showLoading("上传中...");

      const uploadUrl = `${app.globalData.baseUrl}/api/storage/file/${this.data.currentRoomId}`;
      wx.uploadFile({
        url: uploadUrl,
        filePath: file.path,
        name: "file",
        formData: {
          title: file.name,
        },
        success: (res) => {
          if (res.statusCode === 200) {
            app.showToast("上传成功", "success");
            this.loadItems();
          } else {
            app.showToast("上传失败");
          }
        },
        fail: (err) => {
          console.error("上传失败:", err);
          app.showToast(`'${file.name}'上传失败`);
        },
        complete: () => {
          app.hideLoading();
        },
      });
    } catch (error) {
      console.error("上传文件失败:", error);
      app.showToast("上传失败");
      app.hideLoading();
    }
  },

  async syncData() {
    this.setData({ syncing: true });
    try {
      await this.loadItems();
      app.showToast("同步成功", "success");
    } catch (error) {
      app.showToast("同步失败");
    } finally {
      this.setData({ syncing: false });
    }
  },

  // 列表项操作
  viewItem(e) {
    const item = e.currentTarget.dataset.item;
    if (item.type === "file") {
      this.previewFile(e);
    } else {
      // For text, viewing is editing
      this.editItem(e);
    }
  },

  copyItem(e) {
    const item = e.currentTarget.dataset.item;
    let contentToCopy = "";

    if (item.type === "text") {
      contentToCopy = item.content;
    } else if (item.type === "file") {
      contentToCopy = `${this.data.baseUrl}/api/storage/file/${item.id}`;
    }

    wx.setClipboardData({
      data: contentToCopy,
      success: () => {
        app.showToast("已复制", "success");
      },
    });
  },

  previewFile(e) {
    const item = e.currentTarget.dataset.item;

    if (item.isImage) {
      // 预览图片
      wx.previewImage({
        urls: [`${app.globalData.baseUrl}/api/storage/file/${item.id}`],
        current: `${app.globalData.baseUrl}/api/storage/file/${item.id}`,
      });
    } else {
      // 其他文件类型，显示文件信息
      wx.showModal({
        title: "文件信息",
        content: `文件名: ${item.fileName}\n类型: ${
          item.fileType
        }\n大小: ${this.formatSize(item.size)}`,
        showCancel: false,
        confirmText: "关闭",
      });
    }
  },

  editItem(e) {
    const item = e.currentTarget.dataset.item;
    if (item.type === "text") {
      this.showEditTextModal(item);
    } else {
      app.showToast("文件无法直接编辑");
    }
  },

  deleteItem(e) {
    const item = e.currentTarget.dataset.item;

    wx.showModal({
      title: "确认删除",
      content: `确定要删除“${item.title || item.fileName}”吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await app.request({
              url: `/api/storage/items/${item.id}`,
              method: "DELETE",
            });
            app.showToast("删除成功", "success");
            this.loadItems();
          } catch (error) {
            console.error("删除失败:", error);
            app.showToast("删除失败");
          }
        }
      },
    });
  },

  formatSize(bytes) {
    if (!bytes) return "0 B";

    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + " " + sizes[i];
  },

  formatTime(dateString) {
    const seconds = Math.floor((new Date() - new Date(dateString)) / 1000);

    if (seconds < 60) return "刚刚";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}分钟前`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}小时前`;
    const days = Math.floor(hours / 24);
    return `${days}天前`;
  },
});
